package com.ly.datacenter.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.ly.datacenter.component.treeview.pojo.TreeNode;
import com.ly.datacenter.http.util.HttpServletUtil;
import com.ly.datacenter.jdbc.util.DatabaseUtil;

/**
 * Servlet implementation class DatabaseServlet
 */
public class DatabaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String dbname = request.getParameter("x_db");
		System.out.println(dbname);
		HttpServletUtil.configResponseJSON(request, response);
		
		Connection conn = DataSourceContainer.getConnection();
		String[] tableNames = DatabaseUtil.getTableNamesOfDatabase(conn);
		JSONArray array = new JSONArray();
		TreeNode node;
		Map data;
		Map attributes;
		for(String tableName: tableNames){
			node = new TreeNode();
			node.setId(tableName);
			node.setTitle(tableName);
			node.setState("closed");
			data = new HashMap<String,Object>();
			attributes = new HashMap<String, Object>();
			data.put("attributes", attributes);
			attributes.put("href", "table.jsp?table="+tableName);
			attributes.put("target", "content-ifr");
			node.setData(data);
			array.add(node);
		}
		response.getWriter().print(array.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
